--
-- Author: shunguo.chen
-- Date: 2018-06-29 15:22:26
--
-- IMTeamPanel 聊天组队实时语音界面
--

local ClassRef = app.mvc.createPanelClass(...)

local MIC_OPEN_STR = L("lua_code_text_104")
local MIC_CLOSE_STR = L("lua_code_text_305")
local SPEAKER_OPEN_STR = L("lua_code_text_128")
local SPEAKER_CLOSE_STR = L("lua_code_text_63")

function ClassRef.create(node)
	local sprite = ClassRef.extend(node)
	if node == nil then
		ccui.Helper:doLayout(sprite)
	end
	sprite:init()
	return sprite
end

function ClassRef:init(data)
	self.super.init(self, data)

	local timeline = cc.CSLoader:createTimeline(Res.IMTeamNode)
	timeline:setTag(0)
	self:runAction(timeline)
	self._timeline = timeline

	self._ui.tips:setVisible(false)
	self._tipText = self._ui["Panel/tips/tlt"]

	display.setCascadeOpacityEnabled(self._ui.mik, true)
	display.setCascadeOpacityEnabled(self._ui.play, true)

	display.uiAddClick(self._ui.mik_n, function(sender)
		executeFunc(self._onOperate, "mic", true)
	end)

	display.uiAddClick(self._ui.mik, function(sender)
		executeFunc(self._onOperate, "mic", false)
	end)

	display.uiAddClick(self._ui.play_n, function(sender)
		executeFunc(self._onOperate, "speaker", true)
	end)

	display.uiAddClick(self._ui.play, function(sender)
		executeFunc(self._onOperate, "speaker", false)
	end)
end

function ClassRef:refresh(isTeam, hasMic, hasSpeaker)
	self:setVisible(isTeam)
	if isTeam then
		self._ui.mik:setVisible(hasMic)
		self._ui.mik_n:setVisible(not hasMic)
		self._ui.play:setVisible(hasSpeaker)
		self._ui.play_n:setVisible(not hasSpeaker)
		self:refreshAction()
	else
		self:stopAction()
	end
end

function ClassRef:updateMicAndSpeakBtnState(type, open)
	local str, state
	if type == "mic" then
		self._ui.mik:setVisible(open)
		self._ui.mik_n:setVisible(not open)
		str = open and MIC_OPEN_STR or MIC_CLOSE_STR
		state = true
	end
	if type == "speaker" then
		self._ui.play:setVisible(open)
		self._ui.play_n:setVisible(not open)
		str = open and SPEAKER_OPEN_STR or SPEAKER_CLOSE_STR
		state = false
	end
	self:refreshAction()
	self:showTip(str, state)
end

function ClassRef:stopAction()
	self._timeline:gotoFrameAndPause(0)
end

function ClassRef:refreshAction()
	if self._timeline:isPlaying() then return end
	if self._ui.mik:isVisible() or self._ui.play:isVisible() then
		self._timeline:gotoFrameAndPlay(0, true)
	else
		self:stopAction()
	end
end

function ClassRef:showTip(str, isMic)
	self._tipText:setString(str)

	local tips = self._ui.tips
	tips:stopAllActions()
	tips:setVisible(true)
	tips:setOpacity(0)
	tips:setPositionX(isMic and self._ui.mik:getPositionX() or self._ui.play:getPositionX())

	local action = cca.seq({cca.fadeIn(0.3), cca.delay(1), cca.fadeOut(0.3), cca.hide()})
	tips:runAction(action)
end

function ClassRef:onOperate(cb)
	self._onOperate = cb
end

return ClassRef